package org.algorithm.熊猫.树;

import org.algorithm.common.TreeNode;
import org.junit.Test;

import java.util.*;

/**
 * @author jzx
 * @date 2022/5/30
 * @desc {https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/}
 */
public class $6月3二叉树的锯齿形层序遍历 {


    @Test
    public void test() {
        TreeNode treeNode= new TreeNode(3,new TreeNode(9,null,null),new TreeNode(20,new TreeNode(15,null,null),new TreeNode(7,null,null)));
        System.out.println(zigzagLevelOrder(treeNode));
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        Deque<TreeNode> q = new LinkedList<>();
        q.offer(root);

        boolean flag = true;

        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> level = new ArrayList<>();
            if (flag) {
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = q.pollFirst();
                    level.add(treeNode.val);
                    if (treeNode.left != null) {
                        q.offerLast(treeNode.left);
                    }
                    if (treeNode.right != null) {
                        q.offerLast(treeNode.right);
                    }
                }
            } else {
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = q.pollLast();
                    level.add(treeNode.val);
                    if (treeNode.right != null) {
                        q.offerFirst(treeNode.right);
                    }
                    if (treeNode.left != null) {
                        q.offerFirst(treeNode.left);
                    }
                }
            }
            res.add(level);
            flag = !flag;
        }
        return res;
    }

    public List<List<Integer>> zigzagLevelOrder2(TreeNode root) {

        List<List<Integer>> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        Deque<TreeNode> q = new LinkedList<>();
        q.offer(root);

        boolean flag = true;

        while (!q.isEmpty()) {
            int size = q.size();
            ArrayList<Integer> level = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = q.pollFirst();
                    level.add(treeNode.val);
                    if (treeNode.left != null) {
                        q.offerLast(treeNode.left);
                    }
                    if (treeNode.right != null) {
                        q.offerLast(treeNode.right);
                    }
                }
                if(!flag){
                    Collections.reverse(level);
                }
            res.add(level);
            flag = !flag;
        }
        return res;
    }
}
